package com.lu.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.lu.common.core.web.domain.AjaxResult;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @program LuCloud-RuoYi
 * @description: 黑名单过滤器
 * @author: zhanglu
 * @create: 2020-07-01 19:27:00
 */
@Component
public class BlackListUrlFilter extends AbstractGatewayFilterFactory<BlackListUrlFilter.Config> {

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            String url = exchange.getRequest().getURI().getPath();
            if(config.matchBlacklist(url)){ //匹配到黑名单
                ServerHttpResponse response = exchange.getResponse();
                return exchange.getResponse().writeWith(
                        Mono.just(response.bufferFactory().wrap(JSON.toJSONBytes(AjaxResult.error("您已经被拉黑，服务拒绝访问"))))
                );
            }
            return chain.filter(exchange);
        };
    }

    /**
     * TODO 疑问？
     *  - 必须加这段代码，否则 Object -> BlackListUrlFilter.Config 转换失败
     */
    public BlackListUrlFilter()
    {
        super(Config.class);
    }

    public static class Config{

        //nacos配置中心配置
        private List<String> blacklistUrl;
        private List<Pattern> blacklistUrlPattern = new ArrayList<>();

        /**
         * 匹配到黑名单
         * @param url
         * @return
         */
        public boolean matchBlacklist(String url){
            return blacklistUrlPattern.isEmpty() ? false : blacklistUrlPattern.stream()
                    .filter(p -> p.matcher(url).find()).findAny().isPresent();
        }

        public List<String> getBlacklistUrl(){
            return blacklistUrl;
        }

        public void setBlacklistUrl(List<String> blacklistUrl){
            this.blacklistUrl = blacklistUrl;
            this.blacklistUrlPattern.clear();
            this.blacklistUrl.forEach(url -> {
                this.blacklistUrlPattern.add(Pattern.compile(url.replaceAll("\\*\\*", "(.*?)"), Pattern.CASE_INSENSITIVE));
            });
        }

    }

}
